﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using WebOS.Bll;
using WebOSCore.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Asxsyd92Core;
using Microsoft.AspNetCore.Cors;
using Asxsyd92Core.Utils.Provider;
using IdentityModel;
using System.IO;
using System.Net;
using System.Drawing.Imaging;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace WebOSCore.Controllers.Api
{

    public class LoginController : Controller
    {
        [Route("api/ApiLogin/Login")]
        [HttpPost]
        //public async Task<string> Login(string user, string pw)
        //{

        //    var us = UsersBll.Instance.Login(user);
        //    if (us != null)
        //    {
        //        var ps = Asxsyd92Core.Utils.Tools.GetUserEncryptionPassword(user, pw);
        //        // var ps = Asxsyd92Core.Utils.Tools.MD5System(Asxsyd92Core.Utils.Tools.EncryptionPassword(user) + Asxsyd92Core.Utils.Tools.EncryptionPassword(pw));
        //        if (ps == us.Password)
        //        {
        //            if (us.Status == 1)
        //            {
        //                return Newtonsoft.Json.JsonConvert.SerializeObject(new { msg = "用户名被禁用，请联系管理员谢谢！", Success = false });
        //            }
        //            var claims = new List<Claim>();
        //            claims.Add(new Claim(ClaimTypes.Name, us.Name));
        //            claims.Add(new Claim(ClaimTypes.UserData, us.ID.ToString()));
        //            claims.Add(new Claim("Organize", us.Organize));
        //            claims.Add(new Claim("sign", us.sign));
        //            claims.Add(new Claim("avatar", us.avatar));
        //            claims.Add(new Claim("Role", us.Role == null ? "" : us.Role.ID.ToString()));
        //            var identity = new ClaimsIdentity(claims, "login");
        //            var principal = new ClaimsPrincipal(identity);

        //            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal,
        //                   new AuthenticationProperties
        //                   {
        //                       IsPersistent = true,
        //                       ExpiresUtc = DateTimeOffset.Now.Add(TimeSpan.FromDays(180))
        //                   });
        //            if (principal.Identity.IsAuthenticated)
        //            {
        //                return Newtonsoft.Json.JsonConvert.SerializeObject(new { msg = "登录成功！", userid = us.id, name = us.Name, Success = true });
        //            }
        //        }
        //        else
        //        {
        //            return Newtonsoft.Json.JsonConvert.SerializeObject(new { msg = "无效的用户，请输入正确用户！", Success = false });

        //        }
        //    }


        //    return Newtonsoft.Json.JsonConvert.SerializeObject(new { msg = "登录失败！", Success = false });
        //}
        public IActionResult Login(string user, string pw)
        {
            var us = UsersBll.Instance.Login(user);
            if (us != null)
            {
                if (us.Status == 1)
                {
                    return Ok(new
                    {

                        Success = false,
                        msg = "帐号不能使用，已被冻结！",
                    });
                }// Newtonsoft.Json.JsonConvert.SerializeObject(new { msg = "账号不可用！", Success = false }); }

                var ps = Asxsyd92Core.Utils.Tools.MD5System(Asxsyd92Core.Utils.Tools.EncryptionPassword(user) + Asxsyd92Core.Utils.Tools.EncryptionPassword(pw));
                if (ps == us.Password)
                {
                    // var OrganizeID = us.OrganizeID == null ? null : RailwayCore.Dal.OrganizeDal.Instance.Get(us.OrganizeID);
                    var tokenHandler = new JwtSecurityTokenHandler();
                    var key = Encoding.ASCII.GetBytes(AppSetting.GetConfig("JwtSecurityKey"));
                    var authTime = DateTime.UtcNow;
                    var expiresAt = authTime.AddDays(7);
                    var tokenDescriptor = new SecurityTokenDescriptor
                    {
                        Subject = new ClaimsIdentity(new Claim[]
                        {
                    new Claim(JwtClaimTypes.Audience,AppSetting.GetConfig("audience")),
                    new Claim(JwtClaimTypes.Issuer,AppSetting.GetConfig("issuer")),
                    new Claim(JwtClaimTypes.Id, us.ID.ToString()),
                    new Claim(JwtClaimTypes.Name, us.Name),
                   new Claim(JwtClaimTypes.NickName, us.Account),
                     new Claim(JwtClaimTypes.Role, us.Account.ToLower()=="asxsyd92".ToLower()?"110":us.identifier.ToString())
                }),
                        Expires = expiresAt,
                        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                    };
                    var token = tokenHandler.CreateToken(tokenDescriptor);
                    var tokenString = tokenHandler.WriteToken(token);
                    return Ok(new
                    {
                        access_token = tokenString,
                        token_type = "Bearer",
                        msg = "登录成功！",
                        account = us.Account,
                        orid = us.OrganizeID,
                        userid = us.ID.ToString(),
                        orname = us.Organize,
                        name = us.Name,
                        picture = us.avatar,

                        Success = true,
                        profile = new
                        {

                            sid = us.ID.ToString(),
                            name = us.Name,
                            auth_time = new DateTimeOffset(authTime).ToUnixTimeSeconds(),
                            expires_at = new DateTimeOffset(expiresAt).ToUnixTimeSeconds()
                        }
                    });
                }
                else
                {
                    return Ok(new
                    {

                        Success = false,
                        msg = "用户名或者密码错误！",
                    });
                }
            }
            return Ok(new
            {

                Success = false,
                msg = "用户不存在！",
            }); ;

        }
        [Route("api/ApiLogin/qqLogin")]
        [HttpPost]
        public IActionResult qqLogin(string data)
        {
            try
            {
                var fa = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<object, object>>(data);
                if (fa != null)
                {
                    var da = fa.FirstOrDefault(c => c.Key.ToString() == "openid").Value;
                    if (da != null)
                    {
                        //查询openid
                        var ewb = WebOS.Dal.UsersDal.Instance.Get(new { qqopenid = da });
                        if (ewb != null)
                        {
                            var ose = WebOS.Dal.OrganizeDal.Instance.GetList("select o.ID,o.Name from UsersRelation u,Organize o where u.OrganizeID=o.ID and u.ID='" + ewb.ID + "'", null).FirstOrDefault();
                            // var OrganizeID = us.OrganizeID == null ? null : RailwayCore.Dal.OrganizeDal.Instance.Get(us.OrganizeID);
                            var tokenHandler = new JwtSecurityTokenHandler();
                            var key = Encoding.ASCII.GetBytes(AppSetting.GetConfig("JwtSecurityKey"));
                            var authTime = DateTime.UtcNow;
                            var expiresAt = authTime.AddDays(7);
                            var tokenDescriptor = new SecurityTokenDescriptor
                            {
                                Subject = new ClaimsIdentity(new Claim[]
                                {
                          new Claim(JwtClaimTypes.Audience,AppSetting.GetConfig("audience")),
                    new Claim(JwtClaimTypes.Issuer,AppSetting.GetConfig("issuer")),
                    new Claim(JwtClaimTypes.Id, ewb.ID.ToString()),
                    new Claim(JwtClaimTypes.Name, ewb.Name),
                   new Claim(JwtClaimTypes.NickName, ewb.Account),
                     new Claim(JwtClaimTypes.Role, ewb.Account.ToLower()=="asxsyd92".ToLower()?"110":ewb.identifier.ToString())
                        }),
                                Expires = expiresAt,
                                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                            };
                            var token = tokenHandler.CreateToken(tokenDescriptor);
                            var tokenString = tokenHandler.WriteToken(token);
                            return Ok(new
                            {
                                access_token = tokenString,
                                token_type = "Bearer",
                                msg = "登录成功！",
                                account = ewb.Account,
                                userid = ewb.ID.ToString(),
                                orid = ose == null ? Guid.Empty : ose.ID,// ewb.OrganizeID,

                                orname = ose == null ? "未分组" : ose.Name,
                                name = ewb.Name,
                                picture = ewb.avatar,
                                Success = true,
                                profile = new
                                {

                                    sid = ewb.ID.ToString(),
                                    name = ewb.Name,
                                    auth_time = new DateTimeOffset(authTime).ToUnixTimeSeconds(),
                                    expires_at = new DateTimeOffset(expiresAt).ToUnixTimeSeconds()
                                }
                            });
                        }
                        else
                        {
                            //需要绑定帐号
                            return Ok(new
                            {

                                msg = "绑定帐号！",

                                Success = false,

                            });

                        }
                    }
                }
                return Ok(new
                {

                    msg = "登录失败！",

                    Success = false,

                });
            }


            catch (Exception ex)
            {
                return Ok(new
                {

                    msg = ex.Message,

                    Success = false,

                });
            }

        }
        [Route("api/ApiLogin/QqReg")]
        [HttpPost]
        public IActionResult QqReg(string data)
        {
            var fa = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<object, object>>(data);
            if (fa != null)
            {
                Guid usreid = Guid.NewGuid();
                //string avatar= SaveImg(fa.FirstOrDefault(c => c.Key.ToString() == "avatar").Value.ToString(), usreid) ;
                ImgSave(fa.FirstOrDefault(c => c.Key.ToString() == "avatar").Value.ToString(), usreid);
                string avatar = "/images/qq/" + usreid + ".png";
                var da = fa.FirstOrDefault(c => c.Key.ToString() == "openid").Value;
                WebOS.Modle.Users os = new WebOS.Modle.Users();
                os.Account = "";
                os.Name = fa.FirstOrDefault(c => c.Key.ToString() == "username").Value.ToString();
                os.Password = "";
                os.Status = 0;
                os.ID = usreid;
                os.Sort = 1;
                os.qqopenid = da.ToString();
                os.avatar = avatar;
                var ewb = WebOS.Dal.UsersDal.Instance.Get(new { qqopenid = da.ToString() });
                if (ewb == null)
                {
                    if (WebOS.Dal.UsersDal.Instance.Insert(os) > 0)
                    {

                        var ose = WebOS.Dal.OrganizeDal.Instance.GetList("select o.ID,o.Name from UsersRelation u,Organize o where u.OrganizeID=o.ID and u.ID='" + ewb.ID + "'", null).FirstOrDefault();

                        // var OrganizeID = us.OrganizeID == null ? null : RailwayCore.Dal.OrganizeDal.Instance.Get(us.OrganizeID);
                        var tokenHandler = new JwtSecurityTokenHandler();
                        var key = Encoding.ASCII.GetBytes(AppSetting.GetConfig("JwtSecurityKey"));
                        var authTime = DateTime.UtcNow;
                        var expiresAt = authTime.AddDays(7);
                        var tokenDescriptor = new SecurityTokenDescriptor
                        {
                            Subject = new ClaimsIdentity(new Claim[]
                            {
                        new Claim(JwtClaimTypes.Audience,AppSetting.GetConfig("audience")),
                    new Claim(JwtClaimTypes.Issuer,AppSetting.GetConfig("issuer")),
                    new Claim(JwtClaimTypes.Id, ewb.ID.ToString()),
                    new Claim(JwtClaimTypes.Name, ewb.Name),
                   new Claim(JwtClaimTypes.NickName, ewb.Account),
                     new Claim(JwtClaimTypes.Role, ewb.Account.ToLower()=="asxsyd92".ToLower()?"110":ewb.identifier.ToString())
                    }),
                            Expires = expiresAt,
                            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                        };
                        var token = tokenHandler.CreateToken(tokenDescriptor);
                        var tokenString = tokenHandler.WriteToken(token);
                        return Ok(new
                        {
                            access_token = tokenString,
                            token_type = "Bearer",
                            msg = "登录成功！",
                            account = ewb.Account,

                            userid = ewb.ID.ToString(),
                            orid = ose == null ? Guid.Empty : ose.ID,// ewb.OrganizeID,

                            orname = ose == null ? "未分组" : ose.Name,
                            name = ewb.Name,
                            Success = true,
                            profile = new
                            {

                                sid = ewb.ID.ToString(),
                                name = ewb.Name,
                                auth_time = new DateTimeOffset(authTime).ToUnixTimeSeconds(),
                                expires_at = new DateTimeOffset(expiresAt).ToUnixTimeSeconds()
                            }
                        });

                    }


                }
                else
                {
                    ImgSave(fa.FirstOrDefault(c => c.Key.ToString() == "avatar").Value.ToString(), ewb.ID);
                    string avatars = "/images/qq/" + ewb.ID + ".png";

                    os.ID = ewb.ID;
                    os.Password = ewb.Password;
                    os.Account = ewb.Password;
                    os.avatar = avatars;
                    if (WebOS.Dal.UsersDal.Instance.Update(os) > 0)
                    {
                        var ose = WebOS.Dal.OrganizeDal.Instance.GetList("select o.ID,o.Name from UsersRelation u,Organize o where u.OrganizeID=o.ID and u.ID='" + ewb.ID + "'", null).FirstOrDefault();

                        var tokenHandler = new JwtSecurityTokenHandler();
                        var key = Encoding.ASCII.GetBytes(AppSetting.GetConfig("JwtSecurityKey"));
                        var authTime = DateTime.UtcNow;
                        var expiresAt = authTime.AddDays(7);
                        var tokenDescriptor = new SecurityTokenDescriptor
                        {
                            Subject = new ClaimsIdentity(new Claim[]
                            {
                     new Claim(JwtClaimTypes.Audience,AppSetting.GetConfig("audience")),
                    new Claim(JwtClaimTypes.Issuer,AppSetting.GetConfig("issuer")),
                    new Claim(JwtClaimTypes.Id, ewb.ID.ToString()),
                    new Claim(JwtClaimTypes.Name, ewb.Name),
                   new Claim(JwtClaimTypes.NickName, ewb.Account),
                     new Claim(JwtClaimTypes.Role, ewb.Account.ToLower()=="asxsyd92".ToLower()?"110":ewb.identifier.ToString())
                    }),
                            Expires = expiresAt,
                            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                        };
                        var token = tokenHandler.CreateToken(tokenDescriptor);
                        var tokenString = tokenHandler.WriteToken(token);
                        return Ok(new
                        {
                            access_token = tokenString,
                            token_type = "Bearer",
                            msg = "登录成功！",
                            account = ewb.Account,
                            orid = ose == null ? Guid.Empty : ose.ID,// ewb.OrganizeID,

                            orname = ose == null ? "未分组" : ose.Name,
                            userid = ewb.ID.ToString(),

                            name = ewb.Name,
                            Success = true,
                            picture = ewb.avatar,
                            profile = new
                            {

                                sid = ewb.ID.ToString(),
                                name = ewb.Name,
                                auth_time = new DateTimeOffset(authTime).ToUnixTimeSeconds(),
                                expires_at = new DateTimeOffset(expiresAt).ToUnixTimeSeconds()
                            }
                        });

                    };
                };


            }

            return Ok(new
            {

                msg = "登录失败！",

                Success = false,

            });
        }

        [Route("api/ApiLogin/QqBinding")]
        [HttpPost]
        public IActionResult QqBinding(string Account, string Password, string openid, string avatar)
        {
            var us = WebOS.Dal.UsersDal.Instance.Get(new { Account = Account });
            if (us != null)
            {
                if (us.Status == 1) { return Unauthorized(); }// Newtonsoft.Json.JsonConvert.SerializeObject(new { msg = "账号不可用！", Success = false }); }

                var ps = Asxsyd92Core.Utils.Tools.MD5System(Asxsyd92Core.Utils.Tools.EncryptionPassword(Account) + Asxsyd92Core.Utils.Tools.EncryptionPassword(Password));
                if (ps == us.Password)
                {
                    ImgSave(avatar, us.ID);
                    us.avatar = "/images/qq/" + us.ID + ".png";
                    us.qqopenid = openid;

                    if (WebOS.Dal.UsersDal.Instance.Update(us) > 0)
                    {
                        var ose = WebOS.Dal.OrganizeDal.Instance.GetList("select o.ID,o.Name from UsersRelation u,Organize o where u.OrganizeID=o.ID and u.ID='" + us.ID + "'", null).FirstOrDefault();

                        var tokenHandler = new JwtSecurityTokenHandler();
                        var key = Encoding.ASCII.GetBytes(AppSetting.GetConfig("JwtSecurityKey"));
                        var authTime = DateTime.UtcNow;
                        var expiresAt = authTime.AddDays(7);
                        var tokenDescriptor = new SecurityTokenDescriptor
                        {
                            Subject = new ClaimsIdentity(new Claim[]
                            {
                          new Claim(JwtClaimTypes.Audience,AppSetting.GetConfig("audience")),
                    new Claim(JwtClaimTypes.Issuer,AppSetting.GetConfig("issuer")),
                    new Claim(JwtClaimTypes.Id, us.ID.ToString()),
                    new Claim(JwtClaimTypes.Name, us.Name),
                   new Claim(JwtClaimTypes.NickName, us.Account),
                     new Claim(JwtClaimTypes.Role, us.Account.ToLower()=="asxsyd92".ToLower()?"110":us.identifier.ToString())
                    }),
                            Expires = expiresAt,
                            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                        };
                        var token = tokenHandler.CreateToken(tokenDescriptor);
                        var tokenString = tokenHandler.WriteToken(token);
                        return Ok(new
                        {
                            access_token = tokenString,
                            token_type = "Bearer",
                            msg = "登录成功！",
                            account = us.Account,
                            orid = ose == null ? Guid.Empty : ose.ID,// ewb.OrganizeID,

                            orname = ose == null ? "未分组" : ose.Name,
                            userid = us.ID.ToString(),

                            name = us.Name,
                            Success = true,
                            picture = us.avatar,
                            profile = new
                            {

                                sid = us.ID.ToString(),
                                name = us.Name,
                                auth_time = new DateTimeOffset(authTime).ToUnixTimeSeconds(),
                                expires_at = new DateTimeOffset(expiresAt).ToUnixTimeSeconds()
                            }
                        });
                    };
                }
                else
                {
                    return Ok(new
                    {

                        msg = "密码错误！",

                        Success = false,

                    });
                }
            }
            return Ok(new
            {

                msg = "登录失败！",

                Success = false,

            });
        }


        #region 创建目录
        /// <summary>
        /// 创建目录
        /// </summary>
        /// <param name="dir">要创建的目录路径包括目录名</param>
        public static void CreateDir(string dir)
        {
            if (dir.Length == 0) return;
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir)
                 ;
        }
        #endregion
        /// <summary>
        /// 退出登陆
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> SignOut()
        {
            if (HttpContext.User.Identity.IsAuthenticated)
                await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

            return RedirectToAction("/login.html");
        }
        [Route("api/ApiLogin/Get")]
        [Authorize]
        [HttpPost]
        public string Get()
        {
            // The JWT "sub" claim is automatically mapped to ClaimTypes.NameIdentifier
            // by the UseJwtBearerAuthentication middleware
            var username = HttpContext.User.Claims.First(c => c.Type == ClaimTypes.NameIdentifier).Value;

            return $"Hello {username}!";
        }

        /// <summary>
        /// 图片另存为
        /// </summary>
        /// <param name="url">路径</param>
        public void ImgSave(string url, Guid userid)
        {
            try
            {
                WebClient my = new WebClient();
                byte[] mybyte;
                mybyte = my.DownloadData(url);
                MemoryStream ms = new MemoryStream(mybyte);
                System.Drawing.Image img;
                img = System.Drawing.Image.FromStream(ms);
                string m_localPath = AppDomain.CurrentDomain.BaseDirectory;
                string deerory = m_localPath + "wwwroot/images/qq/";
                if (!System.IO.Directory.Exists(deerory))
                {
                    System.IO.Directory.CreateDirectory(deerory);
                }
                img.Save(deerory + userid + ".png", ImageFormat.Png);   //保存
                img.Dispose();

            }
            catch (Exception ex)
            {
                Asxsyd92Core.Utils.Tools.createFile(ex.Message);
            }
        }


    }


}
